package com.scu.dao;

import com.scu.entity.Comment;


import com.scu.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    //添加一个用户
    public int insert(Comment comment) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "INSERT INTO comment(comment_id,comment_content,user_id,date,post_id) VALUES(?,?,?,?,?)";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,comment.getComment_id());
        prep.setString(2,comment.getComment_content());
        prep.setInt(3,comment.getUser_id());
        prep.setString(4,comment.getDate());
        prep.setInt(5,comment.getPost_id());

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }

    //删除
    public int delete(int comment_id) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "delete from comment where comment_id=?";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,comment_id);

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }


    public List<Comment> findAll() throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "select * from comment";
        PreparedStatement prep = conn.prepareStatement(sql);

        //3. 结果
        ResultSet rs = prep.executeQuery();
        //处理结果
        List<Comment> list = new ArrayList<Comment>();
        while(rs.next()){
            //rs代表的就是每一行
            Comment comment = new Comment();
            //根据rs获取每一列的值
            int comment_id = rs.getInt("comment_id");
            String comment_content = rs.getString("comment_content");
            int user_id = rs.getInt("user_id");
            String date =rs.getString("date");
            int post_id = rs.getInt("post_id");

            //把该行每一列的值赋值给user对象
            comment.setComment_id(comment_id);
            comment.setComment_content(comment_content);
            comment.setUser_id(user_id);
            comment.setDate(date);
            comment.setPost_id(post_id);
            System.out.println("dao");
            list.add(comment);
        }

        //4. 关闭连接
        conn.close();

        return list;
    }
    public static void main(String[] args) throws SQLException {
        List<Comment> list = new CommentDao().findAll();
        System.out.println(list);
    }

}

